package com.zero.zerocat;

import com.zero.servlet.ZeroResponse;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.util.internal.StringUtil;

import java.nio.charset.StandardCharsets;

/**
 * ZeroCat中对ZeroResponse的自定义实现类
 */
public class HttpZeroResponse implements ZeroResponse {

    private HttpRequest request;

    private ChannelHandlerContext context;

    public HttpZeroResponse(HttpRequest request, ChannelHandlerContext context){
        this.request = request;
        this.context = context;
    }

    @Override
    public void write(String content) throws Exception {
        // 针对content为空的情况直接返回
        if (StringUtil.isNullOrEmpty(content)){
            return;
        }
        // 创建响应对象
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
            HttpResponseStatus.OK,
            // 根据响应体内容的大小为response对象分配存储空间，并将响应内容包装进ByteBuf中
            Unpooled.wrappedBuffer(content.getBytes(StandardCharsets.UTF_8)));

        // 获取响应头的信息
        HttpHeaders headers = response.headers();

        // 设置响应体类型，响应体长度，缓存过期时间
        headers
            .set(HttpHeaderNames.CONTENT_TYPE, "text/json")
            .set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes())
            .set(HttpHeaderNames.EXPIRES, 0);

        // 如果Http请求是长连接，则响应体也使用长连接
        if (HttpUtil.isKeepAlive(request)){
            headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }
        // 将响应写入到channel中
        context.writeAndFlush(response);
    }
}
